import React,{useCallback} from "react";
import { Button, Checkbox, Form, Input,message} from 'antd';
import { useNavigate,useSearchParams, Link } from "react-router-dom";
import request from "../utils/request";
import {useStorage} from  "../utils/hooks"
import {useDispatch } from "react-redux"

function Login(user){
    const navigate = useNavigate()
    const [SearchParams] = useSearchParams()
    const [useInfo,setUserInfo] = useStorage('userInfo')
    const dispatch = useDispatch()
   
    const onFinish = useCallback((values) => {
        async function userData(){
            console.log(values);
            const {data} = await request.get('/user/login',{
                params:{
                    username:values.username,
                    password:values.password
                }     
            })

            if(data.code === 200){
                message.success('登陆成功！')
                //获取？后面的信息
                const url = SearchParams.get('target') || '/manage/home'
                //登陆成功，存储用户信息
                setUserInfo(data.data)
                dispatch({ type: 'login', payload:data.data })
                navigate(url)
                
            }else if(data.code === 400){
                message.error('用户名或密码错误！')
            }
        }
        
        userData()
      },[]);

    return(
        <main className="login-box" >
        <h3 style={{margin:30,fontSize:20}}>用户登陆</h3>
        <Form
         name="basic"
         labelCol={{ span: 6 }}
         wrapperCol={{ span: 12 }}
         initialValues={{ remember: true }}
         onFinish={onFinish}
         autoComplete="off"
         >
         <Form.Item
             label="用户名"
             name="username"
             rules={[{ required: true, message: '请输入用户名!' }]}
         >
             <Input />
         </Form.Item>
 
         <Form.Item
             label="密码"
             name="password"
             rules={[{ required: true, message: '请输入密码!' }]}
         >
             <Input.Password />
         </Form.Item>
 
         <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 6, span: 12 }}>
             <Checkbox>记住密码</Checkbox>
         </Form.Item>
 
         <Form.Item wrapperCol={{ offset: 6, span: 12 }} > 
             <Button type="primary" htmlType="submit" style={{marginRight:20}}>
             登陆
             </Button >
         </Form.Item>
         </Form>
     </main>
    )
}

export default Login